package com.qdxwx.web.controller.user;

import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.page.PageRequest;
import com.qdxwx.common.utils.ObjectUtils;
import com.qdxwx.common.utils.TKConvert;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.coupon.CouponCodeService;
import com.qdxwx.data.service.coupon.CouponService;
import com.qdxwx.models.coupon.Coupon;
import com.qdxwx.models.coupon.CouponCode;
import com.qdxwx.models.coupon.CouponCodeDTO;
import com.qdxwx.models.coupon.CouponCodeQuery;
import com.qdxwx.models.user.User;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.List;

/**
 * Coupon 优惠券 接口
 * @author developer
 */
@Controller
@RequestMapping("/user")
public class UserCouponController extends BaseController {

    @Autowired
    private CouponCodeService couponCodeService;
    @Autowired
    private CouponService couponService;

    /**
     * 个人中心 我的优惠券
     */
    @RequestMapping("/coupon.html")
    public String myCouPon(HttpServletRequest request) {
        if ("OFF".equals(CacheConstants.COUPON_IS_OPEN)) {
            request.setAttribute("message", "【优惠券】功能未启用！");
            return VIEW_ERROR;
        }
        int currentPage = TKConvert.toInteger(request.getParameter("page"),1);
        // 设置分页参数
        PageRequest page = new PageRequest(currentPage,6);
        CouponCodeQuery couponCodeQuery = new CouponCodeQuery();
        couponCodeQuery.setUserId(LoginUser.getUserId(request));
        couponCodeQuery.setStatus(TKConvert.toInteger(request.getParameter("status")));
        int total = couponCodeService.countCouponCodeDTO(couponCodeQuery);
        request.setAttribute("totalPages", page.getTotalPages(total));
        //查询我的优惠券
        List<CouponCodeDTO> couponList = couponCodeService.getDTOList(couponCodeQuery, page);
        if (couponList != null && couponList.size() > 0) {
            //处理优惠券是否过期
            LocalDate nowDate = LocalDate.now();
            for (CouponCodeDTO couponCodeDTO : couponList) {
                LocalDate endDate = couponCodeDTO.getEndDate();
                if (couponCodeDTO.getStatus() == 1) {
                    //优惠券状态
                    if (nowDate.isAfter(endDate)) {
                        couponCodeDTO.setStatus(3);//过期
                    } else if (nowDate.plusDays(3).isAfter(endDate)) {
                        couponCodeDTO.setStatus(5);//将过期
                    }
                }
            }
        }
        request.setAttribute("page", page);
        request.setAttribute("couponList", couponList);
        request.setAttribute("status", couponCodeQuery.getStatus());
        request.setAttribute("user", LoginUser.getUser(request));
        return getViewPath("ucenter/uc-coupon");
    }

    /**
     * 兑换优惠券
     */
    @RequestMapping("/coupon/active.json")
    @ResponseBody
    public AjaxResult couponActive(HttpServletRequest request) {
        String code = request.getParameter("couponCode");
        if (TKString.isEmpty(code)) return AjaxResult.error("请输入优惠券编码");
        CouponCodeDTO couponCodeDTO = couponCodeService.getDTOByCode(code);
        if (ObjectUtils.isNull(couponCodeDTO)) return AjaxResult.error("请输入正确的优惠券编码");
        if (couponCodeDTO.getStatus() != 1 || couponCodeDTO.getUserId() != 0) return AjaxResult.error("该优惠券已被使用");
        Coupon coupon = couponService.get(couponCodeDTO.getCouponId());
        if (coupon.getUseType() == 1) return AjaxResult.error("在有效期内可以被任意多人使用多次的优惠券，不支持兑换");
        if (!coupon.getEndDate().isAfter(LocalDate.now())) return AjaxResult.error("优惠券已过期");
        User user = LoginUser.getUser(request);
        CouponCode couponCode = couponCodeService.get(couponCodeDTO.getId());
        couponCode.setUserId(user.getUserId());
        couponCode.setUserName(user.getUserName());
        int row = couponCodeService.update(couponCode);
        return row > 0 ? AjaxResult.success() : AjaxResult.error();
    }
}